<!DOCTYPE html>
<html>
<head>
    <title>流式响应测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .message { margin: 10px 0; padding: 10px; border: 1px solid #ccc; }
        .user { background: #e3f2fd; }
        .assistant { background: #f1f8e9; }
        #output { height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; }
        input { width: 300px; padding: 5px; }
        button { padding: 5px 10px; }
    </style>
</head>
<body>
    <h1>流式响应测试</h1>
    <div>
        <input type="text" id="messageInput" placeholder="输入消息..." />
        <button onclick="sendMessage()">发送</button>
    </div>
    <div id="output"></div>

    <script>
        function addMessage(content, type) {
            const output = document.getElementById('output');
            const div = document.createElement('div');
            div.className = `message ${type}`;
            div.textContent = content;
            output.appendChild(div);
            output.scrollTop = output.scrollHeight;
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message) return;

            // 添加用户消息
            addMessage(message, 'user');
            input.value = '';

            // 创建AI消息占位符
            const aiDiv = document.createElement('div');
            aiDiv.className = 'message assistant';
            aiDiv.id = 'ai-message';
            aiDiv.textContent = '';
            document.getElementById('output').appendChild(aiDiv);

            // 发送流式请求
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://localhost:8888/api/ai/chat/send/stream', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('Accept', 'text/event-stream');

            let lastIndex = 0;
            const processChunk = () => {
                const chunk = xhr.responseText.substring(lastIndex);
                if (!chunk) return;
                lastIndex = xhr.responseText.length;

                const lines = chunk.split('\n');
                for (let line of lines) {
                    if (!line) continue;
                    if (line.startsWith('data: ')) {
                        const payload = line.substring(6);
                        if (payload === '[DONE]') {
                            console.log('流式响应完成');
                        } else {
                            try {
                                const parsed = JSON.parse(payload);
                                if (parsed.content) {
                                    console.log('收到内容:', parsed.content);
                                    const aiDiv = document.getElementById('ai-message');
                                    if (aiDiv) {
                                        aiDiv.textContent += parsed.content;
                                    }
                                } else if (parsed.conversationId) {
                                    console.log('收到会话ID:', parsed.conversationId);
                                }
                            } catch (e) {
                                console.log('JSON解析失败:', payload);
                            }
                        }
                    }
                }
            };

            xhr.onprogress = processChunk;
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 3) {
                    processChunk();
                } else if (xhr.readyState === 4) {
                    processChunk();
                }
            };

            xhr.onerror = function() {
                addMessage('请求失败', 'assistant');
            };

            const data = {
                message: message,
                userId: 'test-user',
                conversationId: null,
                createNewConversation: true
            };

            xhr.send(JSON.stringify(data));
        }

        // 回车发送
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>
